﻿using System;
using System.Collections.Generic;
using olierFrm.Extensions.Excel;
using olierFrm.WebFormDev.StdQuery;
using olierFrm.DataBase.FrameWork.StdQuery;
using olierFrm.WebFormDev;
using olierFrm.DataBase;
using System.Linq;

namespace WebFormDev.StdQueryPack
{

    public partial class ExportPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var dbStdQuery = new StdQuerySQL(StdQuery.QueryName);
            foreach (var p in dbStdQuery.StdQueryParams)
            {
                if (p.ParamType == "EndDate" && Request.QueryString[p.ParamName] != null && Request.QueryString[p.ParamName] == "")
                    dbStdQuery.SetParam(p.ParamName, "2100-1-1");
                else if (p.ParamType == "Date" && Request.QueryString[p.ParamName] != null && Request.QueryString[p.ParamName] == "")
                    dbStdQuery.SetParam(p.ParamName, "1900-1-1");
                else dbStdQuery.SetParam(p.ParamName, Request.QueryString[p.ParamName]);
            }
            
            dbStdQuery.AddSystemParams();
            var dtSource = dbStdQuery.ExecuteSQL();
            dtSource.BindCaptionToDataTable();

            if (dbStdQuery.StdQuery.HideFields != null && dbStdQuery.StdQuery.HideFields.Length != 0)
            {
                var hfs = dbStdQuery.StdQuery.HideFields.Split(';');
                foreach (var h in hfs)
                {
                    if (dtSource.Columns.Contains(h))
                        dtSource.Columns.Remove(h);
                }
            }


            //是否显示合计
            List<string> sumFields = new List<string>();
            if ((dbStdQuery.StdQuery.Property & 4) == 4)
                if (dbStdQuery.StdQuery.SumFields != null && dbStdQuery.StdQuery.SumFields.Trim().Length > 0 && dtSource.Rows.Count != 0)
                {
                    sumFields = dbStdQuery.StdQuery.SumFields.Split(';').ToList();
                    if (sumFields.IndexOf("*") != -1)
                    {
                        sumFields.Remove("*");
                    }
                }

            ExcelHelper.ExportByWeb(dtSource, dbStdQuery.StdQuery.ModelName, dbStdQuery.StdQuery.ModelName + ".xls", sumFields);
        }
    }
}